package com.gafker.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.gafker.threads.PrintTask;

public class TaskExecutor {
	public static void main(String[] args) {

		singleThread();//单线程池。
		fixedThread();//固定宽度线程池（访问量有限，采用大队列，小池；小队列池）---权衡
		cachedThread();//无界线程池（内存大，时段访问量过大）

	} // end main
	
	private static void cachedThread() {
		// create and name each runnable
		PrintTask task1 = new PrintTask("task1");
		PrintTask task2 = new PrintTask("task2");
		PrintTask task3 = new PrintTask("task3");
		PrintTask task4 = new PrintTask("task4");
		PrintTask task5 = new PrintTask("task5");
		PrintTask task6 = new PrintTask("task6");
		PrintTask task7 = new PrintTask("task7");
		PrintTask task8 = new PrintTask("task8");
		PrintTask task9 = new PrintTask("task9");

		System.out.println("Starting Executor");

		// create ExecutorService to manage threads
		ExecutorService threadExecutor = Executors.newCachedThreadPool();
		// start threads and place in runnable state
		threadExecutor.execute(task1); // start task1
		threadExecutor.execute(task2); // start task2
		threadExecutor.execute(task3); // start task3
		threadExecutor.execute(task4);
		threadExecutor.execute(task5);
		threadExecutor.execute(task6);
		threadExecutor.execute(task7);
		threadExecutor.execute(task8);
		threadExecutor.execute(task9);
		// shut down worker threads when their tasks complete
		threadExecutor.shutdown();

		System.out.println("Tasks started, main ends.\n");
	}

	private static void fixedThread() {
		System.out.println("============================");
		ExecutorService threadExecutor1 = Executors.newFixedThreadPool(2);
		PrintTask task10 = new PrintTask("task10");
		PrintTask task11 = new PrintTask("task11");
		PrintTask task12 = new PrintTask("task12");
		PrintTask task13 = new PrintTask("task13");
		threadExecutor1.execute(task10);
		threadExecutor1.execute(task11);
		threadExecutor1.execute(task12);
		threadExecutor1.execute(task13);
		threadExecutor1.shutdown();
		System.out.println("============================");
	}

	public static void singleThread() {
		System.out.println("++++++++++++++++++++++++++++");
		ExecutorService threadExecutor2 = Executors.newSingleThreadExecutor();
		PrintTask task14 = new PrintTask("task14");
		PrintTask task15 = new PrintTask("task15");
		PrintTask task16 = new PrintTask("task16");
		PrintTask task17 = new PrintTask("task17");
		threadExecutor2.execute(task14);
		threadExecutor2.execute(task15);
		threadExecutor2.execute(task16);
		threadExecutor2.execute(task17);
		threadExecutor2.shutdown();
		System.out.println("++++++++++++++++++++++++++++");
	}
}
